<template>
  <div ref="chartRef" class="chart" style="height: 100%; width: 100%"></div>
</template>
<script setup>
import * as Echarts from 'echarts'
import { ref, reactive, watchEffect, onMounted } from 'vue'
import { useResizeObserver } from '@vueuse/core'
let myChart = null
let firedNum = ref(0)
let chartRef = ref(null)
let recordOldValue = reactive({
  width: '0',
  height: '0'
})

const chartInit = (opt) => {
  if (!chartRef.value) return
  myChart.setOption(opt)
  let width = props.width || recordOldValue.width
  let height = props.height || recordOldValue.height
  myChart.resize({ width, height })
}
const resize = () => {
  window.addEventListener('resize', () => myChart.resize(), 500)
}

useResizeObserver(chartRef, (entries) => {
  const entry = entries[0]
  const { width, height } = entry.contentRect
  recordOldValue.width = width
  recordOldValue.height = height
  firedNum.value++
})
onMounted(() => {
  myChart = Echarts.init(chartRef.value)
  resize()
  watchEffect(() => {
    let width = props.width || recordOldValue.width
    let height = props.height || recordOldValue.height
    if (firedNum.value) myChart.resize({
      width,
      height
    })
  })
})

const setOption = (opt) => {
  chartInit(opt)
}
defineExpose({ setOption })
const props = defineProps({
  width: {
    type: [String,Number],
    request: false
  },
  height: {
    type: String,
    request: false
  }
})
</script>
<script >
export default {
  name: 'chart'
}
</script>

<style lang="csss" scoped>
</style>
